package com.orangelife.mobile.complaints.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.ToastHelper;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.complaints.adapter.MyHousesAdapter;
import com.orangelife.mobile.constants.HouseURL;
import com.orangelife.mobile.util.JsonReponseHandler;

import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 选择小区,栋座,房号的复用类
 *
 * @author yw
 */
@SuppressWarnings("unchecked")
public class SelectHouseActivity extends OrangeLifeBaseActivity {

    private MyHousesAdapter<Map<String, Object>> adapter;
    private ListView lvzoning;
    private LinearLayout ll;
    private TextView title;
    private Dialog dlgLoading;
    private List<Map<String, Object>> listmap;
    private List<Map<String, Object>> listMapApartment;
    private List<Map<String, Object>> listMapBuilding;
    private List<Map<String, Object>> listMapCity;
    private List<Map<String, Object>> listMapArea;
    private int selectType = SelectHouseActivity.WHAT_CITY;
    private String apartment;
    private String building;
    private String community;
    private String city;
    private String buildID;
    private String commID;
    private String apartmentID;
    private String phone;
    private ZoningHandler handler;
    public static final String INTENT_KEY_ZONING = "zoning";
    public static final int RESULT_CODE_ZONING = 1;
    public static final int WHAT_CITY = 1;//城市
    public static final int WHAT_AREA = 2;//小区
    public static final int WHAT_BUILDING = 3;//楼栋
    public static final int WHAT_APARTMENT = 4;//房号

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_zonning);
        initView();
        findView();
        handler = new ZoningHandler(this);
        getData();
    }


    private void getData() {
        selectType = getIntent().getIntExtra("selectType", 0);
        String value = getIntent().getStringExtra("id");
        switch (selectType) {
            case 1:
                selectCity();
                break;
            case 2:
                city = value;
                selectArea();
                break;
            case 3:
                commID = value;
                selectBuilding();
                break;
            case 4:
                buildID = value;
                selectApartment();
                break;
        }
    }

    private void selectApartment() {
        title.setText("选择房号");
        selectType = WHAT_APARTMENT;
        adapter.setType(selectType);
        HashMap<String, String> map = new HashMap<>();
        map.put("{buildID}", buildID);
        VolleyHttpUtil.getInstance().getWithHandler(HouseURL.APARTMENT_NEW, handler, WHAT_APARTMENT, map);
    }

    private void selectBuilding() {
        title.setText("选择楼栋");
        selectType = WHAT_BUILDING;
        adapter.setType(selectType);
        HashMap<String, String> map = new HashMap<>();
        map.put("{comID}", commID);
        VolleyHttpUtil.getInstance().getWithHandler(HouseURL.BUILDING_NEW, handler, WHAT_BUILDING, map);
    }

    private void selectCity() {
        title.setText("选择城市");
        selectType = WHAT_CITY;
        adapter.setType(selectType);
        VolleyHttpUtil.getInstance().getWithHandler(HouseURL.SERVICE_CITY, handler, WHAT_CITY);
    }

    private void selectArea() {
        title.setText("选择小区");
        selectType = WHAT_AREA;
        adapter.setType(selectType);
        HashMap<String, String> map = new HashMap<>();
        map.put("cityName",city);
        VolleyHttpUtil.getInstance().getWithHandler(HouseURL.SERVICE_COMMUNITY, handler, WHAT_AREA, map);
    }

    static class ZoningHandler extends Handler {
        WeakReference<SelectHouseActivity> wrAct;

        ZoningHandler(SelectHouseActivity act) {
            this.wrAct = new WeakReference<>(act);
        }

        @Override
        public void handleMessage(Message msg) {
            SelectHouseActivity act = wrAct.get();
            if (act != null) {
                switch (msg.what) {
                    case 500:
                        ToastHelper.getInstance()._toast(msg.obj.toString());
                        DialogHelper.closeDialog(act.dlgLoading);
                        break;
                    case 1001:
                        ToastHelper.getInstance()._toast(msg.obj.toString());
                        act.isLogin(act.dlgLoading);
                        break;
                    case WHAT_APARTMENT:
                        act.listMapApartment = JsonReponseHandler.getListFromJson(msg.obj.toString(), act.adapter, act.dlgLoading);
                        break;
                    case WHAT_BUILDING:
                        act.listMapBuilding = JsonReponseHandler.getListFromJson(msg.obj.toString(), act.adapter, act.dlgLoading);
                        break;
                    case WHAT_CITY:
                        act.listMapCity = JsonReponseHandler.getListFromJson(msg.obj.toString(), act.adapter, act.dlgLoading);
                        break;
                    case WHAT_AREA:
                        act.listMapArea = JsonReponseHandler.getListFromJson(msg.obj.toString(), act.adapter, act.dlgLoading);
                        break;
                    default:
                        break;
                }
            }
        }

    }


    /**
     * 设置适配器
     */
    private void setAdapter() {

        listmap = new ArrayList<>();
        adapter = new MyHousesAdapter<>(
                this, listmap, selectType);
        lvzoning.setAdapter(adapter);
    }

    private void initView() {
        title = (TextView) findViewById(R.id.tv_title);
        lvzoning = (ListView) findViewById(R.id.lv_zoning);
        ll = (LinearLayout) findViewById(R.id.ll_score);
        dlgLoading = DialogHelper.getInstance().createLoadingDialog(this);
        dlgLoading.show();
    }

    private void findView() {
        title.setText("城市");
        ll.setVisibility(View.INVISIBLE);
        lvzoning.setOnItemClickListener(itemClickLintener);
        setAdapter();
    }

    /**
     * 选择完成后，跳回原来的界面
     */
    private void jumpBack() {
        Intent intent = new Intent();
        Map<String, Object> map = new HashMap<>();
        map.put("apartment", apartment);
        map.put("apartmentID", apartmentID);
        map.put("building", building);
        map.put("buildID", buildID);
        map.put("city", city);
        map.put("comm", community);
        map.put("commID", commID);
        map.put("phone",phone);
        Bundle bundle = new Bundle();
        bundle.putSerializable(INTENT_KEY_ZONING, (Serializable) map);
        intent.putExtra("selectType",selectType);
        intent.putExtras(bundle);
        setResult(RESULT_OK, intent);
        finish();
    }

    AdapterView.OnItemClickListener itemClickLintener = new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> aview, View view, int position,
                                long arg3) {
            switch (selectType) {
                case WHAT_APARTMENT:
                    dlgLoading.show();
                    apartmentID = listMapApartment.get(position).get("apartmentID").toString();
                    apartment = listMapApartment.get(position).get("apartmentNumb").toString();
                    jumpBack();
                    break;
                case WHAT_BUILDING:
                    dlgLoading.show();
                    buildID = listMapBuilding.get(position).get("buildingID").toString();
                    building = listMapBuilding.get(position).get("buildingName").toString();
                    selectApartment();
                    break;
                case WHAT_AREA:
                    commID = listMapArea.get(position).get("commID").toString();
                    community = listMapArea.get(position).get("comm").toString();
                    phone=listMapArea.get(position).get("phone").toString();
                    selectBuilding();
                    break;
                case WHAT_CITY:
                    city = listMapCity.get(position).get("city").toString();
                    dlgLoading.show();
                    selectArea();
                    break;
                default:
                    break;
            }


        }
    };


    private void updateAdapter(List<Map<String, Object>> listmap) {
        adapter.setList(listmap);
        adapter.notifyDataSetChanged();
    }

    public void onBackClick(View v) {
        updateData();
    }

    @Override
    public void onBackPressed() {
        updateData();
    }

    private void updateData() {
        switch (selectType) {
            case WHAT_APARTMENT:
                if (listMapBuilding == null || listMapBuilding.size() <= 0) {
                    finish();
                } else {
                    selectType = WHAT_BUILDING;
                    adapter.setType(selectType);
                    updateAdapter(listMapBuilding);
                }
                break;
            case WHAT_BUILDING:
                if (listMapArea == null || listMapArea.size() <= 0) {
                    finish();
                } else {
                    selectType = WHAT_AREA;
                    adapter.setType(selectType);
                    updateAdapter(listMapArea);
                }
                break;
            case WHAT_CITY:
                finish();
                break;
            case WHAT_AREA:
                if (listMapCity == null || listMapCity.size() <= 0) {
                    finish();
                } else {
                    selectType = WHAT_CITY;
                    adapter.setType(selectType);
                    updateAdapter(listMapCity);
                }
                break;

            default:
                break;
        }
    }
}